#include <stdio.h>
#include "Hw3Types.h"
#include "Hw3TypesExtended.h"
#include "GlobalVariables.h"
#include "TestFunctions.h"
#include "SyncAndProtectionModule.h"

BOOL OpenImageAndGetProperties(const char* ImageFileName)
{
	// open a reader for the image
	Bmp24LineReader Reader = OpenBmp24LineReader(ImageFileName);
	if (IsInitialized(Reader) == FALSE)
	{
		PrintErrorAndTerminate(ERROR_INITIALIZING_READER);
		return FALSE;
	}

	// fill the data into the appropriate fields in the struct
	ImageReaderAndProperties.Reader = Reader;
	ImageReaderAndProperties.Pitch = GetPitch( Reader );
	ImageReaderAndProperties.Width = GetWidth(Reader);
	ImageReaderAndProperties.Height = GetHeight(Reader);
	ImageReaderAndProperties.Padding = ImageReaderAndProperties.Width%4;
	return TRUE;
}


void CloseImageReaderAndProperties()
{
	// close the reader
	CloseBmp24LineReader(&ImageReaderAndProperties.Reader);
}


TArea *DividePicToAreas( int NumOfAreasHorizontal, int NumOfAreasVertical)
{
	// variable declerations and some calculations
	int i, j;
	int NumOfAreas = NumOfAreasHorizontal*NumOfAreasVertical;
	int LowerMargin = FaceSize.Height;
	int RightMargin = FaceSize.Width;
	int EffectivePicHeight = ImageReaderAndProperties.Height-LowerMargin+1;
	int EffectivePicWidth = ImageReaderAndProperties.Width-RightMargin+1;
	int NormalAreaHeight = EffectivePicHeight/NumOfAreasVertical;
	int NormalAreaWidth = EffectivePicWidth/NumOfAreasHorizontal;
	int LastAreaHeight = EffectivePicHeight-(NumOfAreasVertical-1)*NormalAreaHeight;
	int LastAreaWidth = EffectivePicWidth-(NumOfAreasHorizontal-1)*NormalAreaWidth;

	// allocate memory to contain the areas
	TArea *Areas = (TArea*)malloc(NumOfAreas * sizeof(TArea));
	if (NULL == Areas)
	{
		PrintErrorAndTerminate(ERROR_ALLOCATING_MEMORY);
		return NULL;
	}

	// now create the division itself
	for (i=0 ; i<NumOfAreasVertical ; i++)
	{
		for (j=0 ; j<NumOfAreasHorizontal ; j++)
		{
			TArea *Area = &Areas[NumOfAreasHorizontal*i+j];
			if (i==NumOfAreasVertical-1)
				Area->Height = LastAreaHeight;
			else
				Area->Height = NormalAreaHeight;

			if (j==NumOfAreasHorizontal-1)
				Area->Width = LastAreaWidth;
			else
				Area->Width = NormalAreaWidth;
			
			Area->HorizontalIndex = j;
			Area->VerticalIndex = i;
			Area->OriginX = j*NormalAreaWidth;
			Area->OriginY = i*NormalAreaHeight;
		}
	}

	// for debug mode
	#ifdef DEBUG_MODE
		PrintAreasDivision(Areas, NumOfAreasHorizontal, NumOfAreasVertical);
	#endif

	return Areas;
}

